/**
 * @file 工具方法
 * @module libs/tools
 * @author 月落 <yueluo.yang@qq.com>
 */

/**
 * @requires crypto-js - 加密工具
 * @requires fs - 文件读写模块
 */
const CryptoJS = require('crypto-js'),
      fs = require('fs');

/**
 * @requires config/config - 基础配置
 * @requires config/secert - 秘钥配置
 */
const { hosts } = require('../config/config'),
      { xfyunSecret } = require('../config/secret');

/**
 * @description 获取授权字符串
 * @param {string} date - UTC 格式时间
 * @param {string} uri - api
 * @returns {string}
 */
function getAuthStr (date, uri) {
  const signatureOrigin = `host: ${hosts.xfyunHost}\ndate: ${date}\nGET ${uri} HTTP/1.1`,
        signatureSha = CryptoJS.HmacSHA256(signatureOrigin, xfyunSecret.apiSecret),
        signature = CryptoJS.enc.Base64.stringify(signatureSha),
        authorizationOrigin = `api_key="${xfyunSecret.apiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`,
        authStr = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(authorizationOrigin));
  return authStr;
}

/**
 * @description 组装数据
 * @param {string} vcn - 发言人（默认小燕）
 * @param {number} speed - 发言人速度
 * @param {string} format - 转换格式
 * @param {string} text - 文本
 * @returns {string}
 */
function composeData ({ vcn = 'xiaoyan', speed = 50, format = 'pcm', text }) {
  const audioAssignOpt = {
    pcm: {
      aue: "raw"
    },
    mp3: {
      aue: "lame",
      sfl: 1
    },
    wav: {
      aue: "lame",
      sfl: 1
    }
  };

  return JSON.stringify({
    common: {
      app_id: xfyunSecret.appid
    },
    business: Object.assign({
      auf: 'audio/L16;rate=16000',
      vcn,
      tte: 'UTF8',
      speed
    }, audioAssignOpt[format]),
    data: {
      text: Buffer.from(text).toString('base64'),
      status: 2
    }
  });
}

/**
 * @description 保存文件到本地
 * @param {string} path - 保存路径 
 * @param {object} data - 数据 
 * @returns {promise}
 */
function saveFile ({ path, data }) {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, { flag: 'a' }, (err) => {
      if (err) {
        reject(err);
        console.log(`save error：${err}`);
        return;
      }
      resolve();
      console.log('file save success.', Date.now());
    });
  });
}

// 导出工具方法
module.exports = {
  getAuthStr,
  composeData,
  saveFile
}